package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dto.BehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessage;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author djc
 * @since 2022-10-12
 */
@Service
public class ApLikesBehaviorServiceImpl implements IApLikesBehaviorService {

    @Autowired
    private IApBehaviorEntryService entryService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult saveLikes(BehaviorDto dto) {
        // 获取当前登录的用户
        User user = UserThreadLocalUtil.get();

        ApBehaviorEntry entry = entryService.getEntryByUserIdOrEquipmentId(user.getUserId(),dto.getEquipmentId());

        // 构建点赞行为记录
        ApLikesBehavior behavior = new ApLikesBehavior();
        behavior.setEntryId(entry.getId());
        behavior.setArticleId(dto.getArticleId());
        behavior.setType(0);
        behavior.setOperation(dto.getOperation());
        behavior.setCreatedTime(new Date());
        mongoTemplate.save(behavior);

        UpdateArticleMessage articleMessage = new UpdateArticleMessage();
        articleMessage.setType(1);
        articleMessage.setArticleId(dto.getArticleId());
        articleMessage.setAdd((dto.getOperation() == 0) ? 1 : -1);
        kafkaTemplate.send("hot_article_score_topic", JSON.toJSONString(articleMessage));

        return ResponseResult.okResult();
    }
}
